<?php
/**
 * 药品管理
 * 州弟医院信息系统 - 州弟学安全
 */

// 包含函数文件
require_once '../includes/functions.php';

// 检查用户是否已登录并具有管理员权限
if (!isLoggedIn() || !hasRole('admin')) {
    $_SESSION['error_msg'] = '您无权访问该页面';
    redirect('../login.php');
}

// 处理药品操作
$success = '';
$error = '';

// 处理删除药品请求
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $medicine_id = (int)$_GET['delete'];
    
    // 删除药品
    $sql = "DELETE FROM medicines WHERE id = $medicine_id";
    
    if ($conn->query($sql)) {
        // 记录操作日志
        logAction($_SESSION['user_id'], '删除药品（ID：' . $medicine_id . '）');
        
        $success = '药品删除成功！';
    } else {
        $error = '删除药品失败：' . $conn->error;
    }
}

// 处理预警阈值更新
if (isset($_POST['update_threshold'])) {
    $medicine_id = isset($_POST['threshold_medicine_id']) ? (int)$_POST['threshold_medicine_id'] : 0;
    $threshold = isset($_POST['stock_threshold']) ? (int)$_POST['stock_threshold'] : 10;
    
    if ($medicine_id > 0) {
        $sql = "UPDATE medicines SET stock_threshold = $threshold, updated_at = NOW() WHERE id = $medicine_id";
        
        if ($conn->query($sql)) {
            // 记录操作日志
            logAction($_SESSION['user_id'], '更新药品库存预警阈值（ID：' . $medicine_id . '，阈值：' . $threshold . '）');
            
            $success = '库存预警阈值更新成功！';
        } else {
            $error = '更新库存预警阈值失败：' . $conn->error;
        }
    }
}

// 处理添加批次
if (isset($_POST['add_batch'])) {
    $medicine_id = isset($_POST['batch_medicine_id']) ? (int)$_POST['batch_medicine_id'] : 0;
    $batch_number = $_POST['batch_number'] ?? '';
    $manufacturer_date = $_POST['manufacturer_date'] ?? '';
    $expiry_date = $_POST['expiry_date'] ?? '';
    $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 0;
    $supplier = $_POST['supplier'] ?? '';
    
    if ($medicine_id > 0 && !empty($batch_number) && !empty($expiry_date) && $quantity > 0) {
        // 添加批次记录
        $batch_number = $conn->real_escape_string($batch_number);
        $manufacturer_date = $conn->real_escape_string($manufacturer_date);
        $expiry_date = $conn->real_escape_string($expiry_date);
        $supplier = $conn->real_escape_string($supplier);
        
        $sql = "INSERT INTO medicine_batches (medicine_id, batch_number, manufacturer_date, expiry_date, quantity, supplier, created_at) 
                VALUES ($medicine_id, '$batch_number', '$manufacturer_date', '$expiry_date', $quantity, '$supplier', NOW())";
        
        if ($conn->query($sql)) {
            // 更新药品总库存
            $sql = "UPDATE medicines SET stock = stock + $quantity, updated_at = NOW() WHERE id = $medicine_id";
            $conn->query($sql);
            
            // 记录操作日志
            logAction($_SESSION['user_id'], '添加药品批次（药品ID：' . $medicine_id . '，批次：' . $batch_number . '，数量：' . $quantity . '）');
            
            $success = '药品批次添加成功！';
        } else {
            $error = '添加药品批次失败：' . $conn->error;
        }
    } else {
        $error = '请填写所有必填字段';
    }
}

// 处理添加/编辑药品表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_medicine']) || isset($_POST['edit_medicine'])) {
        $name = $_POST['name'] ?? '';
        $category = $_POST['category'] ?? '';
        $specification = $_POST['specification'] ?? '';
        $manufacturer = $_POST['manufacturer'] ?? '';
        $price = $_POST['price'] ?? '';
        $stock = isset($_POST['stock']) ? (int)$_POST['stock'] : 0;
        $expiry_date = $_POST['expiry_date'] ?? '';
        $description = $_POST['description'] ?? '';
        $medicine_id = isset($_POST['medicine_id']) ? (int)$_POST['medicine_id'] : 0;
        
        // 基本验证
        if (empty($name) || empty($category) || empty($specification)) {
            $error = '请填写所有必填字段';
        } else {
            // 处理表单数据
            $name = $conn->real_escape_string($name);
            $category = $conn->real_escape_string($category);
            $specification = $conn->real_escape_string($specification);
            $manufacturer = $conn->real_escape_string($manufacturer);
            $price = $conn->real_escape_string($price);
            $expiry_date = $conn->real_escape_string($expiry_date);
            $description = $conn->real_escape_string($description);
            
            // 添加新药品
            if (isset($_POST['add_medicine'])) {
                $sql = "INSERT INTO medicines (name, category, specification, manufacturer, price, stock, expiry_date, description, created_at) 
                        VALUES ('$name', '$category', '$specification', '$manufacturer', '$price', $stock, '$expiry_date', '$description', NOW())";
                
                if ($conn->query($sql)) {
                    $new_medicine_id = $conn->insert_id;
                    
                    // 记录操作日志
                    logAction($_SESSION['user_id'], '添加药品（ID：' . $new_medicine_id . '）');
                    
                    $success = '药品添加成功！';
                } else {
                    $error = '添加药品失败：' . $conn->error;
                }
            }
            // 编辑现有药品
            else {
                $sql = "UPDATE medicines SET name = '$name', category = '$category', specification = '$specification', 
                        manufacturer = '$manufacturer', price = '$price', stock = $stock, expiry_date = '$expiry_date', 
                        description = '$description', updated_at = NOW() 
                        WHERE id = $medicine_id";
                
                if ($conn->query($sql)) {
                    // 记录操作日志
                    logAction($_SESSION['user_id'], '更新药品（ID：' . $medicine_id . '）');
                    
                    $success = '药品更新成功！';
                } else {
                    $error = '更新药品失败：' . $conn->error;
                }
            }
        }
    }
}

// 获取所有药品
$medicines = [];
$sql = "SELECT m.*, 
        (SELECT COUNT(*) FROM medicine_batches WHERE medicine_id = m.id) as batch_count,
        (SELECT MIN(expiry_date) FROM medicine_batches WHERE medicine_id = m.id AND quantity > 0) as earliest_expiry
        FROM medicines m ORDER BY name ASC";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // 设置默认预警阈值
        if (!isset($row['stock_threshold'])) {
            $row['stock_threshold'] = 10;
        }
        $medicines[] = $row;
    }
}

// 如果是编辑请求，获取药品信息
$edit_medicine = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $medicine_id = (int)$_GET['edit'];
    $sql = "SELECT * FROM medicines WHERE id = $medicine_id";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $edit_medicine = $result->fetch_assoc();
    }
}

// 获取药品即将过期信息
$expiry_alert = [];
$sql = "SELECT m.id, m.name, mb.batch_number, mb.expiry_date, mb.quantity 
        FROM medicines m 
        JOIN medicine_batches mb ON m.id = mb.medicine_id 
        WHERE mb.expiry_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY) 
        AND mb.quantity > 0 
        ORDER BY mb.expiry_date ASC 
        LIMIT 5";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $expiry_alert[] = $row;
    }
}

// 药品类别列表
$categories = [
    '处方药', '非处方药', '中药', '抗生素', '抗病毒药', '心血管药', '消化系统药', 
    '呼吸系统药', '神经系统药', '泌尿系统药', '内分泌系统药', '维生素矿物质', '外用药', '其他'
];

?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>药品管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/all_3b858821.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 px-0 admin-sidebar">
                <div class="py-3 px-3 bg-dark">
                    <a href="<?php echo SITE_URL; ?>admin/" class="text-white text-decoration-none">
                        <i class="fas fa-hospital-alt mr-2"></i>管理后台
                    </a>
                </div>
                <div class="p-3">
                    <div class="text-white mb-3">
                        <i class="fas fa-user-circle mr-1"></i> <?php echo $_SESSION['username']; ?>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/">
                                <i class="fas fa-tachometer-alt mr-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/users.php">
                                <i class="fas fa-users mr-2"></i>用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/patients.php">
                                <i class="fas fa-user-injured mr-2"></i>患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/doctors.php">
                                <i class="fas fa-user-md mr-2"></i>医生管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/departments.php">
                                <i class="fas fa-hospital mr-2"></i>科室管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/appointments.php">
                                <i class="fas fa-calendar-check mr-2"></i>预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="<?php echo SITE_URL; ?>admin/medicines.php">
                                <i class="fas fa-pills mr-2"></i>药品管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/records.php">
                                <i class="fas fa-notes-medical mr-2"></i>病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/logs.php">
                                <i class="fas fa-history mr-2"></i>系统日志
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>admin/settings.php">
                                <i class="fas fa-cog mr-2"></i>系统设置
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>">
                                <i class="fas fa-home mr-2"></i>返回前台
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="<?php echo SITE_URL; ?>logout.php">
                                <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            
            <!-- 主内容区 -->
            <div class="col-md-10 ml-sm-auto px-4 py-3">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">药品管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-sm btn-outline-secondary mr-2" data-toggle="modal" data-target="#batchManagerModal">
                            <i class="fas fa-layer-group mr-1"></i> 批次管理
                        </button>
                        <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addMedicineModal">
                            <i class="fas fa-plus mr-1"></i> 添加药品
                        </button>
                    </div>
                </div>
                
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <?php echo $success; ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <?php echo $error; ?>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($expiry_alert)): ?>
                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <h5 class="alert-heading"><i class="fas fa-exclamation-triangle mr-1"></i> 药品过期提醒</h5>
                    <p>以下药品即将在30天内过期，请及时处理：</p>
                    <ul class="mb-0">
                        <?php foreach ($expiry_alert as $alert): ?>
                            <li>
                                <strong><?php echo $alert['name']; ?></strong> - 
                                批次 <?php echo $alert['batch_number']; ?> 
                                (数量: <?php echo $alert['quantity']; ?>) 
                                将于 <?php echo date('Y-m-d', strtotime($alert['expiry_date'])); ?> 过期
                            </li>
                        <?php endforeach; ?>
                    </ul>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <?php endif; ?>
                
                <!-- 药品筛选和搜索 -->
                <div class="row mb-4">
                    <div class="col-md-8">
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-secondary btn-sm active filter-btn" data-filter="all">全部</button>
                            <button type="button" class="btn btn-outline-secondary btn-sm filter-btn" data-filter="处方药">处方药</button>
                            <button type="button" class="btn btn-outline-secondary btn-sm filter-btn" data-filter="非处方药">非处方药</button>
                            <button type="button" class="btn btn-outline-secondary btn-sm filter-btn" data-filter="中药">中药</button>
                            <button type="button" class="btn btn-outline-secondary btn-sm filter-btn" data-filter="抗生素">抗生素</button>
                            <button type="button" class="btn btn-outline-info btn-sm filter-btn" data-filter="low-stock">
                                <i class="fas fa-exclamation-triangle"></i> 库存不足
                            </button>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="input-group">
                            <input type="text" class="form-control form-control-sm" id="searchInput" placeholder="搜索药品...">
                            <div class="input-group-append">
                                <button class="btn btn-sm btn-outline-secondary" type="button">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 药品列表 -->
                <div class="row" id="medicineList">
                    <?php if (empty($medicines)): ?>
                        <div class="col-12">
                            <div class="alert alert-info">暂无药品信息</div>
                        </div>
                    <?php else: ?>
                        <?php foreach ($medicines as $medicine): ?>
                            <?php 
                                // 计算是否低于阈值
                                $low_stock = $medicine['stock'] < $medicine['stock_threshold'];
                                // 计算是否有即将过期批次
                                $expiring_soon = !empty($medicine['earliest_expiry']) && 
                                                strtotime($medicine['earliest_expiry']) < strtotime('+30 days');
                            ?>
                            <div class="col-md-4 mb-4 medicine-item" data-category="<?php echo $medicine['category']; ?>" data-stock="<?php echo $medicine['stock']; ?>">
                                <div class="card h-100 <?php echo $low_stock ? 'border-warning' : ($expiring_soon ? 'border-danger' : ''); ?>">
                                    <div class="card-header bg-light">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h5 class="mb-0 text-truncate" title="<?php echo $medicine['name']; ?>"><?php echo $medicine['name']; ?></h5>
                                            <div>
                                                <button type="button" class="btn btn-sm btn-outline-secondary qrcode-btn" data-id="<?php echo $medicine['id']; ?>" data-name="<?php echo $medicine['name']; ?>" title="查看二维码">
                                                    <i class="fas fa-qrcode"></i>
                                                </button>
                                                <a href="?edit=<?php echo $medicine['id']; ?>" class="btn btn-sm btn-info" title="编辑药品">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="?delete=<?php echo $medicine['id']; ?>" class="btn btn-sm btn-danger" title="删除药品" onclick="return confirm('确定要删除此药品吗？此操作不可恢复！');">
                                                    <i class="fas fa-trash-alt"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div class="medicine-info">
                                            <p>
                                                <span class="badge badge-pill badge-primary"><?php echo $medicine['category']; ?></span>
                                                <?php if ($low_stock): ?>
                                                    <span class="badge badge-pill badge-warning">库存不足</span>
                                                <?php endif; ?>
                                                <?php if ($expiring_soon): ?>
                                                    <span class="badge badge-pill badge-danger">即将过期</span>
                                                <?php endif; ?>
                                                <?php if ($medicine['batch_count'] > 0): ?>
                                                    <span class="badge badge-pill badge-info"><?php echo $medicine['batch_count']; ?>个批次</span>
                                                <?php endif; ?>
                                            </p>
                                            <p><strong>规格：</strong><?php echo $medicine['specification']; ?></p>
                                            <p><strong>生产厂家：</strong><?php echo $medicine['manufacturer']; ?></p>
                                            <p><strong>价格：</strong>￥<?php echo number_format($medicine['price'], 2); ?></p>
                                            <p>
                                                <strong>库存：</strong>
                                                <span class="<?php echo $low_stock ? 'text-danger' : ''; ?>">
                                                    <?php echo $medicine['stock']; ?> 件
                                                </span>
                                                <button type="button" class="btn btn-sm btn-link p-0 ml-2 threshold-btn" data-id="<?php echo $medicine['id']; ?>" data-threshold="<?php echo $medicine['stock_threshold']; ?>" title="设置预警阈值">
                                                    <i class="fas fa-bell"></i>
                                                </button>
                                            </p>
                                            <?php if (!empty($medicine['earliest_expiry'])): ?>
                                                <p>
                                                    <strong>最早过期：</strong>
                                                    <span class="<?php echo $expiring_soon ? 'text-danger' : ''; ?>">
                                                        <?php echo date('Y-m-d', strtotime($medicine['earliest_expiry'])); ?>
                                                    </span>
                                                </p>
                                            <?php endif; ?>
                                            <?php if (!empty($medicine['description'])): ?>
                                                <p><strong>描述：</strong><?php echo mb_substr($medicine['description'], 0, 50) . (mb_strlen($medicine['description']) > 50 ? '...' : ''); ?></p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="card-footer bg-white">
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-primary stock-btn" data-id="<?php echo $medicine['id']; ?>" data-name="<?php echo $medicine['name']; ?>" data-stock="<?php echo $medicine['stock']; ?>">
                                                <i class="fas fa-plus-circle mr-1"></i> 更新库存
                                            </button>
                                            <button type="button" class="btn btn-outline-info batch-btn" data-id="<?php echo $medicine['id']; ?>" data-name="<?php echo $medicine['name']; ?>">
                                                <i class="fas fa-layer-group mr-1"></i> 批次管理
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                
                <!-- 高级统计卡片 -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h5 class="mb-0">药品库存分析</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <canvas id="medicineChart" height="200"></canvas>
                            </div>
                            <div class="col-md-6">
                                <h6 class="border-bottom pb-2 mb-3">低库存药品预警</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>药品名称</th>
                                                <th>当前库存</th>
                                                <th>预警阈值</th>
                                                <th>状态</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $counter = 0;
                                            foreach ($medicines as $medicine): 
                                                if ($medicine['stock'] <= $medicine['stock_threshold'] && $counter < 5):
                                                    $counter++;
                                            ?>
                                                <tr>
                                                    <td><?php echo $medicine['name']; ?></td>
                                                    <td><?php echo $medicine['stock']; ?></td>
                                                    <td><?php echo $medicine['stock_threshold']; ?></td>
                                                    <td>
                                                        <span class="badge badge-<?php echo $medicine['stock'] == 0 ? 'danger' : 'warning'; ?>">
                                                            <?php echo $medicine['stock'] == 0 ? '缺货' : '库存低'; ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                            <?php 
                                                endif;
                                            endforeach; 
                                            
                                            if ($counter == 0):
                                            ?>
                                                <tr>
                                                    <td colspan="4" class="text-center">当前没有低库存药品</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 版权信息 -->
                <footer class="mt-5 text-center text-muted">
                    <p>
                        &copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. 版权所有
                        <br>
                        <small>Powered by <a href="#" class="text-muted">州弟学安全</a> | 版本 <?php echo VERSION; ?></small>
                    </p>
                </footer>
            </div>
        </div>
    </div>
    
    <!-- 添加药品模态框 -->
    <div class="modal fade" id="addMedicineModal" tabindex="-1" role="dialog" aria-labelledby="addMedicineModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addMedicineModalLabel">添加药品</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="name">药品名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="name" name="name" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="category">药品类别 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="category" name="category" required>
                                        <option value="">选择类别</option>
                                        <?php foreach ($categories as $category): ?>
                                            <option value="<?php echo $category; ?>"><?php echo $category; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="specification">规格 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="specification" name="specification" placeholder="如：100mg*30片" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="manufacturer">生产厂家</label>
                                    <input type="text" class="form-control" id="manufacturer" name="manufacturer">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="price">价格 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">￥</span>
                                        </div>
                                        <input type="number" class="form-control" id="price" name="price" step="0.01" min="0" required>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="stock">库存数量 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="stock" name="stock" min="0" value="0" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="expiry_date">有效期至</label>
                                    <input type="date" class="form-control" id="expiry_date" name="expiry_date">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="description">药品描述</label>
                            <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="add_medicine" class="btn btn-primary">添加</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 编辑药品模态框 -->
    <?php if ($edit_medicine): ?>
    <div class="modal fade" id="editMedicineModal" tabindex="-1" role="dialog" aria-labelledby="editMedicineModalLabel" aria-hidden="true" data-show="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editMedicineModalLabel">编辑药品</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <input type="hidden" name="medicine_id" value="<?php echo $edit_medicine['id']; ?>">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_name">药品名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="edit_name" name="name" value="<?php echo $edit_medicine['name']; ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_category">药品类别 <span class="text-danger">*</span></label>
                                    <select class="form-control" id="edit_category" name="category" required>
                                        <option value="">选择类别</option>
                                        <?php foreach ($categories as $category): ?>
                                            <option value="<?php echo $category; ?>" <?php echo ($edit_medicine['category'] == $category) ? 'selected' : ''; ?>>
                                                <?php echo $category; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_specification">规格 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="edit_specification" name="specification" value="<?php echo $edit_medicine['specification']; ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_manufacturer">生产厂家</label>
                                    <input type="text" class="form-control" id="edit_manufacturer" name="manufacturer" value="<?php echo $edit_medicine['manufacturer']; ?>">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="edit_price">价格 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">￥</span>
                                        </div>
                                        <input type="number" class="form-control" id="edit_price" name="price" step="0.01" min="0" value="<?php echo $edit_medicine['price']; ?>" required>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="edit_stock">库存数量 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="edit_stock" name="stock" min="0" value="<?php echo $edit_medicine['stock']; ?>" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="edit_expiry_date">有效期至</label>
                                    <input type="date" class="form-control" id="edit_expiry_date" name="expiry_date" value="<?php echo !empty($edit_medicine['expiry_date']) ? date('Y-m-d', strtotime($edit_medicine['expiry_date'])) : ''; ?>">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="edit_description">药品描述</label>
                            <textarea class="form-control" id="edit_description" name="description" rows="3"><?php echo $edit_medicine['description']; ?></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="edit_medicine" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        $(document).ready(function() {
            $('#editMedicineModal').modal('show');
        });
    </script>
    <?php endif; ?>
    
    <!-- 更新库存模态框 -->
    <div class="modal fade" id="updateStockModal" tabindex="-1" role="dialog" aria-labelledby="updateStockModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="updateStockModalLabel">更新库存</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <input type="hidden" id="stock_medicine_id" name="medicine_id">
                        <div class="form-group">
                            <label for="medicine_name">药品名称</label>
                            <input type="text" class="form-control" id="medicine_name" readonly>
                        </div>
                        <div class="form-group">
                            <label for="current_stock">当前库存</label>
                            <input type="number" class="form-control" id="current_stock" readonly>
                        </div>
                        <div class="form-group">
                            <label for="stock_change">库存变更 <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <div class="btn-group btn-group-toggle" data-toggle="buttons">
                                        <label class="btn btn-outline-success active">
                                            <input type="radio" name="stock_action" id="stock_add" value="add" checked> +
                                        </label>
                                        <label class="btn btn-outline-danger">
                                            <input type="radio" name="stock_action" id="stock_subtract" value="subtract"> -
                                        </label>
                                    </div>
                                </div>
                                <input type="number" class="form-control" id="stock_change" name="stock_change" min="1" value="1" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="stock_reason">变更原因</label>
                            <select class="form-control" id="stock_reason" name="stock_reason">
                                <option value="进货">进货</option>
                                <option value="销售">销售</option>
                                <option value="损耗">损耗</option>
                                <option value="退货">退货</option>
                                <option value="盘点调整">盘点调整</option>
                                <option value="其他">其他</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="stock_notes">备注</label>
                            <textarea class="form-control" id="stock_notes" name="stock_notes" rows="2"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="update_stock" class="btn btn-primary">更新</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 库存阈值设置模态框 -->
    <div class="modal fade" id="thresholdModal" tabindex="-1" role="dialog" aria-labelledby="thresholdModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="thresholdModalLabel">设置库存预警阈值</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <input type="hidden" id="threshold_medicine_id" name="threshold_medicine_id">
                        <div class="form-group">
                            <label for="medicine_name_threshold">药品名称</label>
                            <input type="text" class="form-control" id="medicine_name_threshold" readonly>
                        </div>
                        <div class="form-group">
                            <label for="stock_threshold">库存预警阈值 <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="number" class="form-control" id="stock_threshold" name="stock_threshold" min="1" value="10" required>
                                <div class="input-group-append">
                                    <span class="input-group-text">件</span>
                                </div>
                            </div>
                            <small class="form-text text-muted">当库存低于此值时会显示库存不足警告</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="submit" name="update_threshold" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 批次管理模态框 -->
    <div class="modal fade" id="batchManagerModal" tabindex="-1" role="dialog" aria-labelledby="batchManagerModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="batchManagerModalLabel">药品批次管理</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col">
                            <div class="input-group">
                                <select class="form-control" id="selectMedicine">
                                    <option value="">选择药品...</option>
                                    <?php foreach ($medicines as $medicine): ?>
                                        <option value="<?php echo $medicine['id']; ?>"><?php echo $medicine['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" id="loadBatchesBtn">
                                        <i class="fas fa-search"></i> 查询批次
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="col-auto">
                            <button type="button" class="btn btn-primary" id="addBatchBtn">
                                <i class="fas fa-plus"></i> 添加批次
                            </button>
                        </div>
                    </div>
                    
                    <div id="batchesContainer">
                        <div class="text-center py-5 text-muted">
                            <i class="fas fa-layer-group fa-3x mb-3"></i>
                            <p>请选择一个药品查看其批次信息</p>
                        </div>
                    </div>
                    
                    <div id="addBatchForm" style="display: none;">
                        <form method="post" class="border rounded p-3 bg-light">
                            <input type="hidden" id="batch_medicine_id" name="batch_medicine_id">
                            <h6 class="mb-3">添加新批次 - <span id="batch_medicine_name"></span></h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="batch_number">批次编号 <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="batch_number" name="batch_number" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="quantity">数量 <span class="text-danger">*</span></label>
                                        <input type="number" class="form-control" id="quantity" name="quantity" min="1" required>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="manufacturer_date">生产日期</label>
                                        <input type="date" class="form-control" id="manufacturer_date" name="manufacturer_date">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="expiry_date">过期日期 <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="expiry_date" name="expiry_date" required>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="supplier">供应商</label>
                                <input type="text" class="form-control" id="supplier" name="supplier">
                            </div>
                            <div class="form-group mb-0">
                                <button type="submit" name="add_batch" class="btn btn-primary">保存批次</button>
                                <button type="button" class="btn btn-secondary" id="cancelBatchBtn">取消</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 药品二维码模态框 -->
    <div class="modal fade" id="qrcodeModal" tabindex="-1" role="dialog" aria-labelledby="qrcodeModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="qrcodeModalLabel">药品二维码</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body text-center">
                    <div id="qrcodeContainer" class="mb-3"></div>
                    <p class="mb-1" id="qrcodeMedicineName"></p>
                    <small class="text-muted">扫描此二维码可查看药品详细信息</small>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="printQRCode">
                        <i class="fas fa-print mr-1"></i> 打印二维码
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="/assets\js/jquery-3_7b53a2dc.5.1.min.js"></script></script></script></script>
    <script src="/assets\js/popper_9c21e708.min.js"></script></script></script></script>
    <script src="/assets\js/bootstrap_a618e9ff.min.js"></script></script></script></script>
    <script src="/assets\js/Chart_9b2a28ab.min.js"></script></script></script></script>
    <script src="/assets\js/qrcode.min.js"></script></script></script></script>
    <script src="/assets\js/main.js"></script></script>
    <script>
        $(document).ready(function(){
            // 搜索功能
            $("#searchInput").on("keyup", function() {
                var value = $(this).val().toLowerCase();
                $(".medicine-item").filter(function() {
                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
                });
            });
            
            // 药品类别筛选
            $(".filter-btn").click(function() {
                $(".filter-btn").removeClass("active");
                $(this).addClass("active");
                
                var filterValue = $(this).data("filter");
                
                if (filterValue === "all") {
                    $(".medicine-item").show();
                } else if (filterValue === "low-stock") {
                    $(".medicine-item").hide();
                    $(".medicine-item").each(function() {
                        if (parseInt($(this).data("stock")) < 10) {
                            $(this).show();
                        }
                    });
                } else {
                    $(".medicine-item").hide();
                    $('.medicine-item[data-category="' + filterValue + '"]').show();
                }
            });
            
            // 更新库存模态框
            $(".stock-btn").click(function() {
                var id = $(this).data("id");
                var name = $(this).data("name");
                var stock = $(this).data("stock");
                
                $("#stock_medicine_id").val(id);
                $("#medicine_name").val(name);
                $("#current_stock").val(stock);
                
                $("#updateStockModal").modal("show");
            });
            
            // 库存预警阈值设置
            $(".threshold-btn").click(function() {
                var id = $(this).data("id");
                var threshold = $(this).data("threshold");
                var name = $(this).closest(".medicine-info").prev().find("h5").text();
                
                $("#threshold_medicine_id").val(id);
                $("#medicine_name_threshold").val(name);
                $("#stock_threshold").val(threshold);
                
                $("#thresholdModal").modal("show");
            });
            
            // 批次管理
            $(".batch-btn").click(function() {
                var id = $(this).data("id");
                var name = $(this).data("name");
                
                $("#selectMedicine").val(id);
                loadBatches(id);
                
                $("#batchManagerModal").modal("show");
            });
            
            // 加载批次信息
            $("#loadBatchesBtn").click(function() {
                var medicineId = $("#selectMedicine").val();
                if (medicineId) {
                    loadBatches(medicineId);
                }
            });
            
            // 显示添加批次表单
            $("#addBatchBtn").click(function() {
                var medicineId = $("#selectMedicine").val();
                var medicineName = $("#selectMedicine option:selected").text();
                
                if (medicineId) {
                    $("#batch_medicine_id").val(medicineId);
                    $("#batch_medicine_name").text(medicineName);
                    $("#batchesContainer").hide();
                    $("#addBatchForm").show();
                } else {
                    alert("请先选择一个药品");
                }
            });
            
            // 取消添加批次
            $("#cancelBatchBtn").click(function() {
                $("#addBatchForm").hide();
                $("#batchesContainer").show();
            });
            
            // 药品二维码生成
            $(".qrcode-btn").click(function() {
                var id = $(this).data("id");
                var name = $(this).data("name");
                
                $("#qrcodeContainer").empty();
                $("#qrcodeMedicineName").text(name);
                
                // 生成二维码
                new QRCode(document.getElementById("qrcodeContainer"), {
                    text: `${window.location.origin}${window.location.pathname}?medicine=${id}`,
                    width: 200,
                    height: 200,
                    colorDark: "#000000",
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel.H
                });
                
                $("#qrcodeModal").modal("show");
            });
            
            // 打印二维码
            $("#printQRCode").click(function() {
                var printContents = document.getElementById('qrcodeContainer').outerHTML;
                var medicineName = document.getElementById('qrcodeMedicineName').textContent;
                
                var printWindow = window.open('', '_blank');
                printWindow.document.write('<html><head><title>药品二维码</title>');
                printWindow.document.write('<style>body { text-align: center; font-family: Arial, sans-serif; } h3 { margin-top: 20px; }</style>');
                printWindow.document.write('</head><body>');
                printWindow.document.write(printContents);
                printWindow.document.write('<h3>' + medicineName + '</h3>');
                printWindow.document.write('</body></html>');
                printWindow.document.close();
                printWindow.focus();
                
                setTimeout(function() {
                    printWindow.print();
                    printWindow.close();
                }, 500);
            });
            
            // 药品库存图表
            var ctx = document.getElementById('medicineChart').getContext('2d');
            var medicineChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['充足库存', '低库存', '缺货'],
                    datasets: [{
                        data: [
                            <?php 
                                $adequate = 0;
                                $low = 0;
                                $empty = 0;
                                
                                foreach ($medicines as $medicine) {
                                    if ($medicine['stock'] == 0) {
                                        $empty++;
                                    } else if ($medicine['stock'] < $medicine['stock_threshold']) {
                                        $low++;
                                    } else {
                                        $adequate++;
                                    }
                                }
                                
                                echo "$adequate, $low, $empty";
                            ?>
                        ],
                        backgroundColor: [
                            'rgba(75, 192, 192, 0.7)',
                            'rgba(255, 193, 7, 0.7)',
                            'rgba(255, 99, 132, 0.7)'
                        ],
                        borderColor: [
                            'rgba(75, 192, 192, 1)',
                            'rgba(255, 193, 7, 1)',
                            'rgba(255, 99, 132, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    legend: {
                        position: 'right'
                    }
                }
            });
            
            // 加载批次信息函数
            function loadBatches(medicineId) {
                // 在实际应用中，应该通过AJAX从服务器获取批次信息
                // 这里仅作为示例，模拟批次数据
                
                var medicineName = $("#selectMedicine option[value='" + medicineId + "']").text();
                
                setTimeout(function() {
                    var batchesHtml = `
                        <h6 class="mb-3">${medicineName} 的批次信息</h6>
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm">
                                <thead class="thead-light">
                                    <tr>
                                        <th>批次编号</th>
                                        <th>生产日期</th>
                                        <th>过期日期</th>
                                        <th>数量</th>
                                        <th>供应商</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>B2023001</td>
                                        <td>2023-01-15</td>
                                        <td>2025-01-15</td>
                                        <td>50</td>
                                        <td>广州医药有限公司</td>
                                        <td><span class="badge badge-success">正常</span></td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-outline-danger">消耗</button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>B2023002</td>
                                        <td>2023-03-10</td>
                                        <td>2025-03-10</td>
                                        <td>30</td>
                                        <td>广州医药有限公司</td>
                                        <td><span class="badge badge-success">正常</span></td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-outline-danger">消耗</button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>B2023003</td>
                                        <td>2023-06-05</td>
                                        <td>2023-12-05</td>
                                        <td>5</td>
                                        <td>上海医疗器械有限公司</td>
                                        <td><span class="badge badge-danger">即将过期</span></td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-outline-danger">消耗</button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <p class="text-muted small mt-2">注：药品按批次先进先出原则进行消耗</p>
                    `;
                    
                    $("#batchesContainer").html(batchesHtml).show();
                    $("#addBatchForm").hide();
                }, 300);
            }
        });
    </script>
</body>
</html> 